package com.example.mvc.service;

import com.example.mvc.bean.Brand;
import com.example.mvc.mapper.BrandMapper;
import com.example.mvc.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandService {

    private SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    //查询所有
    public List<Brand> selectAll(){
        //获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //调用方法
        List<Brand> brands = mapper.selectAll();
        sqlSession.close();
        return brands;
    }

    //插入
    public  int add(Brand brand){
        //获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //调用添加方法
        int count = mapper.add(brand);
        //提交
        sqlSession.commit();
        //释放
        sqlSession.close();

        return count;

    }

    //通过id查询Brand
    public Brand getBrandById(Integer id){
        //获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //调用查询方法
        Brand brand = mapper.getBrandById(id);
       return  brand;
    }

    public int update(Brand brand) {
        //获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //调用添加方法
        int count = mapper.upate(brand);
        //提交
        sqlSession.commit();
        return count;
    }

    //删除
    public int deleteById(int id){
        //调用BrandMapper.selectAll()
        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4. 调用方法
        int count = mapper.deleteById(id);
        //提交事务
        sqlSession.commit();
        sqlSession.close();
        return count;
    }
}
